<template>
  <div class="middle-container">
    <div class="widget-form-container scroll">
      <el-form
        :label-position="widgetData.config.labelPosition || 'right'"
        :label-width="widgetData.config.labelWidth + 'px'"
        size="small"
        class="widget-form"
      >
        <draggable
          v-model="widgetData.list"
          v-bind="{ group: 'formMake', ghostClass: 'ghost', animation: 0, handle: '.drag-widget' }"
          :move="handelMove"
          class="widget-list"
          item-key="name"
          tag="div"
          filter="form-empty"
          @add="handleWidgetAdd"
        >
          <div v-for="(element, index) in widgetData.list" :key="element.key">
            <FormMakeGrid v-if="element.type === 'grid'" :widget-data="widgetData" :element-parent="element" is-pre-view @handleWidgetClone="handleWidgetClone($event, index)" @handleWidgetDelete="handleWidgetDelete"/>
            <FormMakeItem v-else :element="element" :form-options="widgetData" is-pre-view is-middle @handleWidgetClone="handleWidgetClone($event, index)" @handleWidgetDelete="handleWidgetDelete" />
          </div>
          <div v-if="widgetData.list.length === 0" slot="footer" class="form-empty">
            <img :src="emptyIcon" alt="">
            <div class="label">从左侧拖拽添加字段</div>
          </div>
        </draggable>
      </el-form>
    </div>
  </div>
</template>

<script>
import draggable from 'vuedraggable';
import FormMakeItem from './components/FormMakeItem';
import FormMakeGrid from './components/FormMakeGrid';
import { EventBus } from '@/utils/eventBus';
import { mapState } from 'vuex';
import emptyIcon from '@/assets/process/zhuashou.png';
import LimitMove from '@/views/legal/process/components/formMake/components/mixins/limitMove';

export default {
  name: 'FormMakeMiddle',
  components: { draggable, FormMakeItem, FormMakeGrid },
  mixins: [LimitMove],
  model: {
    prop: 'widgetData',
    event: 'changeData'
  },
  props: {
    widgetData: {
      type: Object,
      default: () => {
        return {
          list: [],
          config: { labelWidth: 100, labelPosition: 'right' }
        };
      }
    }
  },
  data() {
    return { emptyIcon };
  },
  computed: {
    ...mapState({
      'selectWidget': state => state.formMake.selectWidget
    })
  },
  methods: {
    handleWidgetAdd(evt) {
      // 只有从左边和子表单拖出来才算是新增
      if (evt.from.className.indexOf('widget-left-components') < 0 && evt.from.className.indexOf('widget-subtable') < 0) {
        return;
      }
      let newIndex = evt.newIndex;
      if (!newIndex && newIndex !== 0) return;
      if (newIndex >= this.widgetData.list.length) newIndex--;
      const widgetItem = this.extendsProps(this.widgetData.list[newIndex]);
      // 当职位组件从外部移入子表单，需要重置跟随人员字段
      if (widgetItem.type === 'post' && widgetItem.options.follower) {
        widgetItem.options.follower = null;
      }
      this.widgetData.list[newIndex] = widgetItem;
      this.$store.dispatch('setSelectWidget', widgetItem);
      this.changeData();
      this.$forceUpdate();
      EventBus.$emit('formOptionsChange', { type: 'add', data: _.cloneDeep(widgetItem) });
    },
    extendsProps(item) {
      // 为拖拽到容器的元素添加唯一 key
      const key = new Date().valueOf() + '_' + Math.ceil(Math.random() * 99999);
      const cloneItem = _.cloneDeep(item);
      // 给新添加进来的组件，添加新的属性，但是为了不影响原数据，所以深拷贝
      if (!cloneItem.key) {
        cloneItem.key = key;
        cloneItem._isNew = true;
      }
      if (cloneItem.isSubTable) {
        delete cloneItem.isSubTable;
        delete cloneItem.linkFormKey;
        delete cloneItem.subformFullName;
      }
      return cloneItem;
    },
    /**
     * 操作
     */
    changeData() {
      this.$emit('changeData', this.widgetData);
    },
    handleWidgetClone(element, index) {
      const cloneElement = _.cloneDeep(element);
      if (cloneElement.type === 'grid' && cloneElement.columns.length) {
        // 重制栅格子组件的key
        cloneElement.columns.forEach(col => {
          if (col.list && col.list.length) {
            col.list.forEach(gridEl => {
              delete gridEl.isFilter;
              gridEl.key = new Date().valueOf() + '_' + Math.ceil(Math.random() * 99999);
            });
          }
        });
      } else if (cloneElement.type === 'subform' && cloneElement.subform.length) {
        // 重制子表单的子组件key
        cloneElement.subform.forEach(gridEl => {
          delete gridEl.isFilter;
          gridEl._isNew = true;
          gridEl.key = new Date().valueOf() + '_' + Math.ceil(Math.random() * 99999);
        });
      }
      const key = new Date().valueOf() + '_' + Math.ceil(Math.random() * 99999);
      cloneElement.key = key;
      cloneElement._isNew = true;
      delete cloneElement.isFilter;
      this.widgetData.list.splice(index, 0, cloneElement);
      this.changeData();
      this.$store.dispatch('setSelectWidget', cloneElement);
      EventBus.$emit('formOptionsChange', { type: 'add', data: _.cloneDeep(cloneElement), isClone: true });
    },
    handleWidgetDelete(element) {
      const key = element.key;
      const index = this.widgetData.list.findIndex(i => i.key === key);
      if (index >= 0) {
        this.widgetData.list.splice(index, 1);
      }
      EventBus.$emit('formOptionsChange', { type: 'remove', data: _.cloneDeep(element) });
      this.changeData();
      if (this.widgetData.list.length) {
        this.$store.dispatch('setSelectWidget', this.widgetData.list[0]);
      } else {
        this.$store.dispatch('setSelectWidget', null);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
@import './components/mixins/style.scss';
.middle-container {
  flex:1;
  max-width: calc(100% - 320px - 270px);
  padding-bottom: 20px;
  &::v-deep {
    .el-form--label-top {
      .el-form-item {
        padding: 0 10px;
      }
    }
  }
}
.widget-form-container {
  height: 100%;
  position: relative;
  // border: 1px dashed #999;
  .form-empty {
    position: absolute;
    width: calc(100% - 32px);
    height: calc(100% - 32px);
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
    margin: 16px;
    top: 0;
    left: 0;
    border: 1px dashed #999999;
    border-radius: 8px;
    .label {
      color: #999;
      font-size: 16px;
    }
    img {
      width: 60px;
      height: 60px;
    }
  }
}
.widget-form {
  background: #f5f5f5;
  height: 100%;
  .widget-list {
    height: 100%;
  }
}
.scroll {
  @include scrollBar($x: hidden, $y: auto, $width: 6px);
}
</style>
